package com.leo.chapter07;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

import static java.util.concurrent.TimeUnit.SECONDS;

/**
 * 用boolean状态值来保存取消状态
 *  简单的取消策略
 * @author xuexiaolei
 * @version 2017年10月16日
 */
public class PrimeGenerator implements Runnable {
    private final List<BigInteger> primes = new ArrayList<>();
    private volatile boolean cancelled;//记录取消状态

    @Override public void run() {
        BigInteger p = BigInteger.ONE;
        while (!cancelled){
            p = p.nextProbablePrime();
            synchronized (this){
                primes.add(p);
            }
        }
    }

    public void cancell(){ cancelled = true; }
    public synchronized List<BigInteger> get(){
        return new ArrayList<>(primes);
    }

    /**
     * 只运行一秒的素数生成器
     * @return
     * @throws InterruptedException
     */
    public static List<BigInteger> aSecondOfPrimes() throws InterruptedException{
        PrimeGenerator generator = new PrimeGenerator();
        new Thread(generator).start();
        try {
            SECONDS.sleep(1);
        }finally {
            generator.cancell();
        }

        return generator.get();
    }

    public static void main(String[] args) throws InterruptedException {
        List<BigInteger> bigIntegers = aSecondOfPrimes();
        for (BigInteger a : bigIntegers) {
            System.out.println(a.toString());
        }
    }
}
